package com.easytake.emotioncat.controller;

import com.easytake.emotioncat.constant.NumberConstants;
import com.easytake.emotioncat.dto.MiniAppLoginResponse;
import com.easytake.emotioncat.dto.Response;
import com.easytake.emotioncat.service.MiniAppService;
import com.easytake.emotioncat.service.impl.EmUserInfoServiceImpl;
import com.easytake.emotioncat.util.WxCacheUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.Objects;

@Tag(name = "微信交互接口")
@RestController
@RequestMapping("/mini_app")
public class MiniAppController {

    @Autowired
    private MiniAppService miniAppService;

    @Autowired
    private EmUserInfoServiceImpl userInfoService;

    @Operation(summary = "登录微信获取用户校验token")
    @PostMapping("/login")
    @Parameter(name = "code", description = "wxcode")
    public Response<String> login(@NotNull String code) {
        MiniAppLoginResponse response = miniAppService.authCode2Session(code);
        if (NumberConstants.ZERO.equals(response.getErrcode()) || Objects.isNull(response.getErrcode())) {
            userInfoService.addUserIfNewVisitAsync(response.getOpenid());
            String token = WxCacheUtil.addCache(code, response.getOpenid(), response.getSession_key());
            return Response.success(token);
        }
        return Response.fail(response.getErrmsg());
    }

    @Operation(summary = "清理过期token")
    @DeleteMapping("/token")
    @Parameter(name = "token", description = "token")
    public Response<String> logout(@NotNull String token) {
        WxCacheUtil.clearToken(token);
        return Response.success();
    }

}
